package com.foreveross.fetl.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateUtils {

	/**
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String format(Date date, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return sdf.format(date);
	}

	/**
	 * 获得指定日期的前一天
	 * 
	 * @param specifiedDay
	 * @return
	 * @throws Exception
	 */
	public static Date getSpecifiedDayBefore(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		int day = c.get(Calendar.DATE);
		c.set(Calendar.DATE, day - 1);
		return c.getTime();
	}
	public static void main(String[] args) {
		System.out.println(getSpecifiedDayBefore(new Date()));
		
	}

	/**
	 * 
	 * @param source
	 * @param pattern
	 * @return
	 */
	public static Date parse(String source, String pattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			return sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String timeInMillis2Time(Long diff){
		   long diffMinutes = diff / (60 * 1000)%60; 
		   long diffHours = diff / (60 * 60 * 1000); 
		   String hour ="";
		   String min="";
		   if(diffHours<10){
			   hour="0"+diffHours;
		   }else{
			   hour=""+diffHours;
		   }
		   if(diffMinutes<10){
			   min="0"+diffMinutes;
		   }else{
			   min=""+diffMinutes;
		   }
		   return hour+":"+min;
	   }
	
	/**
	    * 计算两个时间差
	    * @param start
	    * @param end
	    * @return
	    */
	public static  String dateDifference(Date start,Date end){
		   if(null ==start || null== end){
			   return "00:00";
		   }
		   Calendar cstart = Calendar.getInstance(); 
		   Calendar cend = Calendar.getInstance();
		   cstart.setTime(start);
		   cend.setTime(end);
		   long millisecondsStart =cstart.getTimeInMillis();
		   long millisecondsEnd =cend.getTimeInMillis();
		   long diff =millisecondsEnd-millisecondsStart;
		   if(diff<=0){
			   return "00:00";
		   }
		   return timeInMillis2Time(diff);
		   
	   }


}
